package com.eascs.ant.data.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.ant.common.controller.BaseMasterViewController;
import com.eascs.ant.data.entity.news.NewsResult;
import com.eascs.ant.data.entity.phone.JdPhoneResult;
import com.eascs.ant.data.entity.phone.ZolPhoneResult;
import com.eascs.ant.data.entity.price.NcPriceResult;
import com.eascs.ant.data.platform.Platform;
import com.eascs.ant.data.service.NewsService;
import com.eascs.ant.data.service.PriceService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertErrorUtils;
import com.eascs.site.view.ViewContext;

/**
 * 数据展示控制层
 * @author hzp
 *
 */
@Controller
public class DataViewController  extends BaseMasterViewController{

	private static Logger logger = LoggerFactory.getLogger(DataViewController.class);
	
	@Inject
	NewsService ns;
	
	@Inject
	PriceService ps;
	
	@RequestMapping("/news")
	public String getSocial() {
		//进入舆情页面，先检索出各平台最新新闻
		List<NewsResult> nrs = ns.queryLatestNews();
		ViewContext.put("nrs", nrs);
		return "/home/news";
	}
	
	@RequestMapping("/price")
	public String getPrice() {
		//进入价格行情页面，先检索出新农商网价格行情数据前几条
		List<NcPriceResult> nps = ps.queryNcPrice();
		ViewContext.put("nps", nps);
		return "/home/price";
	}
	
	@RequestMapping("/news/search")
	public String searchNews(){
		
		return "/view/news/news_result";
	}
	
	
	@RequestMapping("/price/download")
	public void download(String platform ,String date , HttpServletResponse response, HttpServletRequest request) throws IOException ,ParseException{
		logger.info("查询日期:{} ,平台:{}" ,date ,platform);
		if(platform.equals(Platform.NC_PRICE.getPlatform())){
			downloadNcPrice(date , request ,response);
		}else if(platform.equals(Platform.ZOL_PHONE.getPlatform())){
			downloadZolPhone(date ,request ,response);
		}else if(platform.equals(Platform.JINGDONG_PHONE.getPlatform())){
			downloadJdPhone(date, request, response);
		}
	}

	/**
	 * 下载京东手机信息
	 * @param date
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ParseException
	 */
	private void downloadJdPhone(String date, HttpServletRequest request ,HttpServletResponse response) throws IOException ,ParseException{
		String excelName = "京东手机价格信息表";
		List<JdPhoneResult> jprs = ps.queryJdPhone(date);
		AssertErrorUtils.assertTrue(jprs.size()>0, "不好意思,京东手机行情没有{}的数据", date);
	    HSSFWorkbook wb = new HSSFWorkbook();
	    HSSFSheet sheet = wb.createSheet();
	    HSSFRow row = sheet.createRow(0);
	    
	    //设置单元格为时间格式 yyyy-MM-dd
	    HSSFDataFormat hdf = wb.createDataFormat();
	    HSSFCellStyle date_style = wb.createCellStyle();
	    date_style.setDataFormat(hdf.getFormat("yyyy-MM-dd"));;
	    
	    //2,创建表头
	    row.createCell(0).setCellValue("商品名");
	    row.createCell(1).setCellValue("价格");
	    row.createCell(2).setCellValue("店铺");
	    row.createCell(3).setCellValue("评论数");
	    row.createCell(4).setCellValue("品牌");
	    row.createCell(5).setCellValue("销售类型");
	    row.createCell(6).setCellValue("url");
	    
	    //3,循环写入数据
	    for(int i=0;i<jprs.size();i++){
	    	row = sheet.createRow(i+1);
	    	JdPhoneResult jpr = jprs.get(i);
	    	row.createCell(0).setCellValue(jpr.getName());
	    	row.createCell(1).setCellValue(jpr.getPrice());
	    	row.createCell(2).setCellValue(jpr.getShop());
	    	row.createCell(3).setCellValue(jpr.getCommit());
	    	row.createCell(4).setCellValue(jpr.getLogo());
	    	row.createCell(5).setCellValue(jpr.getIcon());
	    	row.createCell(6).setCellValue(jpr.getUrl());
	    }
	    
	    writeWbToResponse(response, excelName + ".xls", wb);		
	}
	
	/**
	 * 下载新农商网价格行情数据
	 * @param date
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ParseException
	 */
	private void downloadNcPrice(String date , HttpServletRequest request ,HttpServletResponse response) throws IOException ,ParseException{
		String excelName = "农商价格信息表";
		List<NcPriceResult> ncprs = ps.queryNcPrice(date);
		AssertErrorUtils.assertTrue(ncprs.size()>0, "不好意思,农商网价格没有{}的数据", date);
	    HSSFWorkbook wb = new HSSFWorkbook();
	    HSSFSheet sheet = wb.createSheet();
	    HSSFRow row = sheet.createRow(0);
	    
	    //设置单元格为时间格式 yyyy-MM-dd
	    HSSFDataFormat hdf = wb.createDataFormat();
	    HSSFCellStyle date_style = wb.createCellStyle();
	    date_style.setDataFormat(hdf.getFormat("yyyy-MM-dd"));;
	    
	    //2,创建表头
	    row.createCell(0).setCellValue("日期");
	    row.createCell(1).setCellValue("市场");
	    row.createCell(2).setCellValue("产品");
	    row.createCell(3).setCellValue("价格");
	    row.createCell(4).setCellValue("走势");
	    
	    HSSFCell cell = null;
	    //3,循环写入数据
	    for(int i=0;i<ncprs.size();i++){
	    	row = sheet.createRow(i+1);
	    	NcPriceResult npr = ncprs.get(i);
	    	cell = row.createCell(0);//日期
	    	cell.setCellValue(npr.getDate());
	    	cell.setCellStyle(date_style);
	    	row.createCell(1).setCellValue(npr.getMarket());
	    	row.createCell(2).setCellValue(npr.getProduct());
	    	row.createCell(3).setCellValue(npr.getPrice());
	    	row.createCell(4).setCellValue(npr.getTrend());
	    }
	    
	    writeWbToResponse(response, excelName + ".xls", wb);
	}
	
	/**
	 * 下载中关村手机行情数据
	 * @param date
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ParseException
	 */
	private void downloadZolPhone(String date, HttpServletRequest request ,HttpServletResponse response) throws IOException ,ParseException{
		List<ZolPhoneResult> zprs = ps.queryZolPhone(date);
		AssertErrorUtils.assertTrue(zprs.size()>0, "不好意思,中关村手机行情没有{}的数据", date);
	    String excelName = "中关村手机价格信息表";
		HSSFWorkbook wb = new HSSFWorkbook();
	    HSSFSheet sheet = wb.createSheet(excelName);
	    HSSFRow row = sheet.createRow(0);
	    
	
	    //设置单元格为时间格式 yyyy-MM-dd
	    HSSFDataFormat hdf = wb.createDataFormat();
	    HSSFCellStyle date_style = wb.createCellStyle();
	    date_style.setDataFormat(hdf.getFormat("yyyy-MM-dd"));;
	    
	    //2,创建表头
	    row.createCell(0).setCellValue("名称");
	    row.createCell(1).setCellValue("品牌");
	    row.createCell(2).setCellValue("价格");
	    row.createCell(3).setCellValue("发布时间");
	    row.createCell(4).setCellValue("CPU型号");
	    row.createCell(5).setCellValue("电池容量");
	    row.createCell(6).setCellValue("主屏尺寸");
	    row.createCell(7).setCellValue("CPU频率");
	    row.createCell(8).setCellValue("操作系统");
	    row.createCell(9).setCellValue("4G网络");
	    row.createCell(10).setCellValue("RAM容量");
	    row.createCell(11).setCellValue("ROM容量");
	    row.createCell(12).setCellValue("参考报价");
	    row.createCell(13).setCellValue("商家报价");
	    row.createCell(14).setCellValue("在售电商报价之京东");
	    row.createCell(15).setCellValue("在售电商报价之天猫商城");
	    row.createCell(16).setCellValue("在售电商报价之ZOL商城");
	    row.createCell(17).setCellValue("链接");
	    row.createCell(18).setCellValue("底价链接");
	    //3,循环写入数据
	    for(int i=0;i<zprs.size();i++){
	    	row = sheet.createRow(i+1);
	    	ZolPhoneResult zpr = zprs.get(i);
	    	row.createCell(0).setCellValue(zpr.getName());
	    	row.createCell(1).setCellValue(zpr.getBrand());
	    	row.createCell(2).setCellValue(zpr.getPrice());
	    	row.createCell(3).setCellValue(zpr.getPublishTime());
	    	row.createCell(4).setCellValue(zpr.getCpuXinghao());
	    	row.createCell(5).setCellValue(zpr.getDianchirongliang());
	    	row.createCell(6).setCellValue(zpr.getZhupingchicun());
	    	row.createCell(7).setCellValue(zpr.getCpuPinlv());
	    	row.createCell(8).setCellValue(zpr.getCaozuoxitong());
	    	row.createCell(9).setCellValue(zpr.getForGnetType());
	    	row.createCell(10).setCellValue(zpr.getRamRongliang());
	    	row.createCell(11).setCellValue(zpr.getRomRongliang());
	    	row.createCell(12).setCellValue(zpr.getCankaobaojia());
	    	row.createCell(13).setCellValue(zpr.getShangjiabaojia());
	    	row.createCell(14).setCellValue(zpr.getZaishoudianshang_jingdong());
	    	row.createCell(15).setCellValue(zpr.getZaishoudianshang_tmall());
	    	row.createCell(16).setCellValue(zpr.getZaishoudianshang_zol());
	    	row.createCell(17).setCellValue(zpr.getUrl());
	    	row.createCell(18).setCellValue(zpr.getLow_price_url());
	    	
	    }
	    
		writeWbToResponse(response, excelName +".xls", wb);
	}
	
	/**
	 * 将制作好的HSSFWorkbook写入response
	 * @param response
	 * @param fileName ，注意文件名后缀,xxx.xls
	 * @param wb
	 * @throws IOException
	 */
	private void writeWbToResponse(HttpServletResponse response , String fileName ,HSSFWorkbook wb) throws IOException{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
 
        try {
          bis = new BufferedInputStream(is);
          bos = new BufferedOutputStream(out);
          byte[] buff = new byte[2048];
          int bytesRead;
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        	  bos.write(buff, 0, bytesRead);
          }
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
          if (bis != null)
              bis.close();
          if (bos != null)
              bos.close();
        }		
	}
	
	/*private void writeToLocal(HSSFWorkbook wb , String filePath) throws IOException{
		//下载本地
	    FileOutputStream out =new FileOutputStream(filePath);
	    wb.write(out); 
	    out.close();
	}*/
}

